

package sg.edu.nus.iss.phoenix.schedule.controller;
/**
 * @author Sanghrajka Vipul - A0092656W
 *
 */
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sg.edu.nus.iss.phoenix.authenticate.entity.User;
import sg.edu.nus.iss.phoenix.schedule.entity.Utility;
import sg.edu.nus.iss.phoenix.schedule.delegate.MaintainScheduleDelegate;
import sg.edu.nus.iss.phoenix.schedule.entity.AnnualSchedule;
import sg.edu.nus.iss.phoenix.schedule.entity.ProgramSlot;
import sg.edu.nus.iss.phoenix.schedule.entity.WeeklySchedule;
import sg.edu.nus.iss.phoenix.schedule.service.MaintainScheduleService;

/**
 * Servlet implementation class ScheduleController
 */
@WebServlet("/ScheduleController/*")
public class ScheduleController extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ScheduleController() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doProcess(request, response);
	}



	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doProcess(request, response);
	}
	
	private void doProcess(HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		String selection = request.getParameter("selection");
		int actionValue = new Integer(selection).intValue();
		User user = (User) request.getSession().getAttribute("user");

		long user_val = user.getId();	
		String yearOfSchedule = null;
		String week_number = null; 	
		MaintainScheduleDelegate msd = null;
		//System.out.println("CASE 1 - Create Schedule - Year = "+yearOfSchedule +" week = "+week_number);
		
		int week = 0;
		int year = 0;
		
		WeeklySchedule ws = null;
		AnnualSchedule as = null;
		ArrayList<ProgramSlot> arrPS= null;
		ProgramSlot ps ;
		try{
		switch (actionValue) {
		case Utility.CREATE_SCHEDULE:
		System.out.println("ScheduleController case CREATE_SCHEDULE START");
		

		// - YEAR - annual_year
		// - Week number - week_number
		// - selection below value - this drives the logic
		//for Create Schedule, set a value of 1
		//for copy Schedule, set a value of 2
		//for modify schedule - set value of 3
		//for delete schedule - set value of 4
		// list of start day - start_week_day
		// list of startTime Hours - start_time_hh
		// list of startTime Minutes - start_time_mm
		// list of end Time hours - end_time_hh
		// list of end Time minutes - end_time_mm
		// list of end day - end_week_day
		// list radio programs - programs_list
		// list presenters - presenter_list
		// list producers - producer_list
		
		//find weekly schedule
		 yearOfSchedule = request.getParameter("annual_year");
		 week_number =  request.getParameter("week_number"); 	
		 msd = new MaintainScheduleDelegate();
		System.out.println("CASE 1 - Create Schedule - Year = "+yearOfSchedule +" week = "+week_number);
		
		 week = new Integer(yearOfSchedule).intValue();
		 year = new Integer(yearOfSchedule).intValue();
		
		ws = new WeeklySchedule();
		ws.setWeekNumber(week);
		ws.setYear(year);
		System.out.println("CASE 1 - Create Schedule - WeeklySchedule Objected Created");
		
		if(msd.findAnnualSchedule(year).getYear() == -1 ){
			as = new AnnualSchedule();
			as.setYear(year);
			msd.createAnnualSchedule(as, user);
			
		}
		
		if(msd.findWeeklySchedule(ws).getId() == -1){
			arrPS = new ArrayList<ProgramSlot>();
			
			System.out.println("CASE 1 - Create Schedule - Existing WeeklySchedule NOT FOUND");
			System.out.println("CASE 1 - Create Schedule - Setting Program Slot in WeeklySchedule");
			
			String start_week_day[] = request.getParameterValues("start_week_day");
			String start_time_hh[] = request.getParameterValues("start_time_hh");
			String start_time_mm[] = request.getParameterValues("start_time_mm");
			String end_time_hh[] = request.getParameterValues("end_time_hh");
			String end_time_mm[] = request.getParameterValues("end_time_mm");
			String end_week_day[] = request.getParameterValues("end_week_day");
			String programs_list[] = request.getParameterValues("programs_list");
			String presenter_list[] = request.getParameterValues("presenter_list");
			String producer_list[] = request.getParameterValues("producer_list");
			
			System.out.println("CASE 1 - Create Schedule - all request parameters assigned to Variables");
			System.out.println("CASE 1 - Create Schedule - request parameters - start_week_day:"+ start_week_day.length);
			System.out.println("CASE 1 - Create Schedule - request parameters - start_time_hh:"+ start_time_hh.length);
			System.out.println("CASE 1 - Create Schedule - request parameters - start_time_mm:"+ start_time_mm.length);
			System.out.println("CASE 1 - Create Schedule - request parameters - end_time_hh:"+ end_time_hh.length);
			System.out.println("CASE 1 - Create Schedule - request parameters - end_time_mm:"+ end_time_mm.length);
			System.out.println("CASE 1 - Create Schedule - request parameters - programs_list:"+ programs_list.length);
			System.out.println("CASE 1 - Create Schedule - request parameters - producer_list:"+ producer_list.length);
			
			
			int day = 0;
			int hh = 0;
			int mm = 0;
			
			
			for (int i=0;i<programs_list.length;i++){
				System.out.println("CASE 1 - Create Schedule - request parameters - Inside for loop :"+ i);
				ps = new ProgramSlot();
				ps.setPresenterId(new Long(presenter_list[i]).longValue());
				System.out.println("CASE 1 - Create Schedule - request parameters - Inside for loop getPresenterId :"+ ps.getPresenterId());
				ps.setProducerId (new Long(producer_list[i]).longValue());
				System.out.println("CASE 1 - Create Schedule - request parameters - Inside for loop getProducerId :"+ ps.getProducerId());
				ps.setRadioProgramId(new Long(programs_list[i]).longValue());
				
				day = new Integer(start_week_day[i]).intValue();
				
				ps.setDateofWeek(Utility.getDateforWeekDayYear(week, day, year));
				hh = new Integer(start_time_hh[i]).intValue();
				mm = new Integer(start_time_mm[i]).intValue();
				ps.setStartTime(Utility.getTimeOfDay(hh,mm));
				
				hh = new Integer(end_time_hh[i]).intValue();
				mm = new Integer(end_time_mm[i]).intValue();
				ps.setEndTime(Utility.getTimeOfDay(hh,mm));

				//day = new Integer(end_week_day[i]).intValue();
				
				
				ps.setId(user_val);
				arrPS.add(ps);
			}
			System.out.println("CASE 1 - Create Schedule - request parameters - Inside Out of for loop" );
			ws.setProgramSlotsforWeek(arrPS);
			System.out.println("CASE 1 - Create Schedule - setProgramSlotsforWeek done" );			
			ws.setUser_id(user_val);
			ws.setId(new Long(""+year+week).longValue());
			try {
				System.out.println("CASE 1 - Create Schedule - calling  msd.saveWeeklySchedule(ws)" );
				msd.saveWeeklySchedule(ws);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				System.out.println("CASE 1 - Create Schedule - calling  msd.saveWeeklySchedule(ws) called ERROR" );
				e.printStackTrace();
				request.setAttribute("DISPLAY_MESSAGE", "Weekly Creation has generated error");
				RequestDispatcher req = getServletContext().getRequestDispatcher("/pages/crudSchedule.jsp");
				req.forward(request, response);
			}
//			success
			System.out.println("CASE 1 - Create Schedule - calling  msd.saveWeeklySchedule(ws) called success" );
			request.setAttribute("DISPLAY_MESSAGE", "Weekly Creation Been created Schedule id is "+ws.getId());
			RequestDispatcher req = getServletContext().getRequestDispatcher("/pages/crudSchedule.jsp");
			req.forward(request, response);
		}
		else{
			request.setAttribute("DISPLAY_MESSAGE", "Weekly Schedule Exists. Please select different week/year");
			RequestDispatcher req = getServletContext().getRequestDispatcher("/pages/crudSchedule.jsp");
			req.forward(request, response);
		}
		
		
		// find weekly schedule
		// create weekly weekly schedule
		
			break;
//----------------------------------------------------------------------------------------------------------
		case Utility.COPY_SCHEDULE:
			System.out.println("ScheduleController case COPY_SCHEDULE START");
			 yearOfSchedule = request.getParameter("annual_year");
			 week_number =  request.getParameter("week_number"); 	
			 msd = new MaintainScheduleDelegate();
			System.out.println("CASE 2 - COPY Schedule - Year = "+yearOfSchedule +" week = "+week_number);
			
			 week = new Integer(yearOfSchedule).intValue();
			 year = new Integer(yearOfSchedule).intValue();
			
			 ws = new WeeklySchedule();
			ws.setWeekNumber(week);
			ws.setYear(year);
			System.out.println("CASE 2 - COPY Schedule - WeeklySchedule Objected Created");
			if(msd.findAnnualSchedule(year).getYear() == -1 ){
				as = new AnnualSchedule();
				as.setYear(year);
				msd.createAnnualSchedule(as, user);
				
			}
			
			if(msd.findWeeklySchedule(ws).getId() == -1){
				arrPS = new ArrayList<ProgramSlot>();
				
				System.out.println("CASE 2 - COPY Schedule - Existing WeeklySchedule NOT FOUND");
				System.out.println("CASE 2 - COPY Schedule - Setting Program Slot in WeeklySchedule");
				
				String start_week_day[] = request.getParameterValues("start_week_day");
				String start_time_hh[] = request.getParameterValues("start_time_hh");
				String start_time_mm[] = request.getParameterValues("start_time_mm");
				String end_time_hh[] = request.getParameterValues("end_time_hh");
				String end_time_mm[] = request.getParameterValues("end_time_mm");
				String end_week_day[] = request.getParameterValues("end_week_day");
				String programs_list[] = request.getParameterValues("programs_list");
				String presenter_list[] = request.getParameterValues("presenter_list");
				String producer_list[] = request.getParameterValues("producer_list");
				
				System.out.println("CASE 2 - COPY Schedule - all request parameters assigned to Variables");
				System.out.println("CASE 2 - COPY Schedule - request parameters - start_week_day:"+ start_week_day.length);
				System.out.println("CASE 2 - COPY Schedule - request parameters - start_time_hh:"+ start_time_hh.length);
				System.out.println("CASE 2 - COPY Schedule - request parameters - start_time_mm:"+ start_time_mm.length);
				System.out.println("CASE 2 - COPY Schedule - request parameters - end_time_hh:"+ end_time_hh.length);
				System.out.println("CASE 2 - COPY Schedule - request parameters - end_time_mm:"+ end_time_mm.length);
				System.out.println("CASE 2 - COPY Schedule - request parameters - programs_list:"+ programs_list.length);
				System.out.println("CASE 2 - COPY Schedule - request parameters - producer_list:"+ producer_list.length);
				

				int day = 0;
				int hh = 0;
				int mm = 0;
				
				
				for (int i=0;i<programs_list.length;i++){
					System.out.println("CASE 2 - COPY Schedule - request parameters - Inside for loop :"+ i);
					ps = new ProgramSlot();
					ps.setPresenterId(new Long(presenter_list[i]).longValue());
					System.out.println("CASE 2 - COPY Schedule - request parameters - Inside for loop getPresenterId :"+ ps.getPresenterId());
					ps.setProducerId (new Long(producer_list[i]).longValue());
					System.out.println("CASE 2 - COPY Schedule - request parameters - Inside for loop getProducerId :"+ ps.getProducerId());
					ps.setRadioProgramId(new Long(programs_list[i]).longValue());
					
					day = new Integer(start_week_day[i]).intValue();
					
					ps.setDateofWeek(Utility.getDateforWeekDayYear(week, day, year));
					hh = new Integer(start_time_hh[i]).intValue();
					mm = new Integer(start_time_mm[i]).intValue();
					ps.setStartTime(Utility.getTimeOfDay(hh,mm));
					
					hh = new Integer(end_time_hh[i]).intValue();
					mm = new Integer(end_time_mm[i]).intValue();
					ps.setEndTime(Utility.getTimeOfDay(hh,mm));

					//day = new Integer(end_week_day[i]).intValue();
					
					
					ps.setId(user_val);
					arrPS.add(ps);
				}
				System.out.println("CASE 2 - COPY Schedule - request parameters - Inside Out of for loop" );
				ws.setProgramSlotsforWeek(arrPS);
				System.out.println("CASE2 - COPY Schedule - setProgramSlotsforWeek done" );			
				ws.setUser_id(user_val);
				ws.setId(new Long(""+year+week).longValue());
				try {
					System.out.println("CASE 2 - COPY Schedule - calling  msd.saveWeeklySchedule(ws)" );
					msd.saveWeeklySchedule(ws);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					System.out.println("CASE 2 - COPY Schedule - calling  msd.saveWeeklySchedule(ws) called ERROR" );
					e.printStackTrace();
					request.setAttribute("DISPLAY_MESSAGE", "Weekly Creation has generated error");
					RequestDispatcher req = getServletContext().getRequestDispatcher("/pages/copySchedule.jsp");
					req.forward(request, response);
				}
//				success
				System.out.println("CASE 2 - COPY Schedule - calling  msd.saveWeeklySchedule(ws) called success" );
				request.setAttribute("DISPLAY_MESSAGE", "Weekly Schedule has been Copied ");
				RequestDispatcher req = getServletContext().getRequestDispatcher("/pages/copySchedule.jsp");
				req.forward(request, response);
			}
			else{
				request.setAttribute("DISPLAY_MESSAGE", "Weekly Schedule Exists. Please select different week/year");
				RequestDispatcher req = getServletContext().getRequestDispatcher("/pages/copySchedule.jsp");
				req.forward(request, response);
			}
			
			
			// find weekly schedule
			// create weekly weekly schedule			
			
			break;
//----------------------------------------------------------------------------------------------------------
		case Utility.DELETE_SCHEDULE:
			System.out.println("ScheduleController case DELETE_SCHEDULE START");
			//check if the week is current week
			 yearOfSchedule = request.getParameter("annual_year");
			 week_number =  request.getParameter("week_number"); 	

			System.out.println("CASE 3 - delete Schedule - Year = "+yearOfSchedule +" week = "+week_number);
			
			 week = new Integer(yearOfSchedule).intValue();
			 year = new Integer(yearOfSchedule).intValue();
			
			 ws = new WeeklySchedule();
			ws.setWeekNumber(week);
			ws.setYear(year);
			System.out.println("CASE 3 - Delete Schedule - WeeklySchedule Objected created");
			if(Utility.getCurrentWeek() == week){
				System.out.println("CASE 3 - Delete Schedule - deleted week is current week" );
				request.setAttribute("DISPLAY_MESSAGE", "Deletion of current week is not allowed");
				RequestDispatcher req = getServletContext().getRequestDispatcher("/pages/deleteSchedule.jsp");
				req.forward(request, response);
			}
			else{
				 msd = new MaintainScheduleDelegate();
				 try{
				 msd.deleteWeeklySchedule(ws);
				 }
				 catch(Exception e){
						System.out.println("CASE 3 - Delete Schedule - Error inm deletion" );
						request.setAttribute("DISPLAY_MESSAGE", "Error in deletion");
						RequestDispatcher req = getServletContext().getRequestDispatcher("/pages/deleteSchedule.jsp");
						req.forward(request, response);
				 }
					System.out.println("CASE 3 - Delete Schedule -Delete Successful" );
					request.setAttribute("DISPLAY_MESSAGE", "Deletion Successful for Week "+ws.getWeekNumber());
					RequestDispatcher req = getServletContext().getRequestDispatcher("/pages/deleteSchedule.jsp");
					req.forward(request, response); 
			}
			
			break;
//----------------------------------------------------------------------------------------------------------
		case Utility.MODIFY_SCHEDULE:
			System.out.println("ScheduleController case MODIFY_SCHEDULE START");
			 yearOfSchedule = request.getParameter("annual_year");
			 week_number =  request.getParameter("week_number"); 	
			 msd = new MaintainScheduleDelegate();
			System.out.println("CASE 4 - Modify Schedule - Year = "+yearOfSchedule +" week = "+week_number);
			
			 week = new Integer(yearOfSchedule).intValue();
			 year = new Integer(yearOfSchedule).intValue();
			
			 ws = new WeeklySchedule();
			ws.setWeekNumber(week);
			ws.setYear(year);
			System.out.println("CASE 4 - Modify Schedule - WeeklySchedule Objected Created");
			if(msd.findAnnualSchedule(year).getYear() != -1 ){
				as = new AnnualSchedule();
				as.setYear(year);
				msd.createAnnualSchedule(as, user);
				
			}
			else{
				System.out.println("CASE 4 - Modify Schedule - calling  msd.saveWeeklySchedule(ws) called ERROR" );
				request.setAttribute("DISPLAY_MESSAGE", "Weekly Schedule Modify has generated error");
				RequestDispatcher req = getServletContext().getRequestDispatcher("/pages/modifySchedule.jsp");
				req.forward(request, response);
				return;
			}
			
			if(msd.findWeeklySchedule(ws).getId() != -1){
				arrPS = new ArrayList<ProgramSlot>();
				
				System.out.println("CASE 4 - Modify Schedule - Existing WeeklySchedule NOT FOUND");
				System.out.println("CASE 4 - Modify Schedule - Setting Program Slot in WeeklySchedule");
				
				String start_week_day[] = request.getParameterValues("start_week_day");
				String start_time_hh[] = request.getParameterValues("start_time_hh");
				String start_time_mm[] = request.getParameterValues("start_time_mm");
				String end_time_hh[] = request.getParameterValues("end_time_hh");
				String end_time_mm[] = request.getParameterValues("end_time_mm");
				String end_week_day[] = request.getParameterValues("end_week_day");
				String programs_list[] = request.getParameterValues("programs_list");
				String presenter_list[] = request.getParameterValues("presenter_list");
				String producer_list[] = request.getParameterValues("producer_list");
				
				System.out.println("CASE 4 - Modify Schedule - all request parameters assigned to Variables");
				System.out.println("CASE 4 - Modify Schedule - request parameters - start_week_day:"+ start_week_day.length);
				System.out.println("CASE 4 - Modify Schedule - request parameters - start_time_hh:"+ start_time_hh.length);
				System.out.println("CASE 4 - Modify Schedule - request parameters - start_time_mm:"+ start_time_mm.length);
				System.out.println("CASE 4 - Modify Schedule - request parameters - end_time_hh:"+ end_time_hh.length);
				System.out.println("CASE 4 - Modify Schedule - request parameters - end_time_mm:"+ end_time_mm.length);
				System.out.println("CASE 4 - Modify Schedule - request parameters - programs_list:"+ programs_list.length);
				System.out.println("CASE 4 - Modify Schedule - request parameters - producer_list:"+ producer_list.length);
				

				int day = 0;
				int hh = 0;
				int mm = 0;
				
				
				for (int i=0;i<programs_list.length;i++){
					System.out.println("CASE 4 - Modify Schedule - request parameters - Inside for loop :"+ i);
					ps = new ProgramSlot();
					ps.setPresenterId(new Long(presenter_list[i]).longValue());
					System.out.println("CASE 4 - Modify Schedule - request parameters - Inside for loop getPresenterId :"+ ps.getPresenterId());
					ps.setProducerId (new Long(producer_list[i]).longValue());
					System.out.println("CASE4 - Modify Schedule - request parameters - Inside for loop getProducerId :"+ ps.getProducerId());
					ps.setRadioProgramId(new Long(programs_list[i]).longValue());
					
					day = new Integer(start_week_day[i]).intValue();
					
					ps.setDateofWeek(Utility.getDateforWeekDayYear(week, day, year));
					hh = new Integer(start_time_hh[i]).intValue();
					mm = new Integer(start_time_mm[i]).intValue();
					ps.setStartTime(Utility.getTimeOfDay(hh,mm));
					
					hh = new Integer(end_time_hh[i]).intValue();
					mm = new Integer(end_time_mm[i]).intValue();
					ps.setEndTime(Utility.getTimeOfDay(hh,mm));

					//day = new Integer(end_week_day[i]).intValue();
					
					
					ps.setId(user_val);
					arrPS.add(ps);
				}
				System.out.println("CASE 4 - Modify Schedule - request parameters - Inside Out of for loop" );
				ws.setProgramSlotsforWeek(arrPS);
				System.out.println("CASE 4 - Modify Schedule - setProgramSlotsforWeek done" );			
				ws.setUser_id(user_val);
				ws.setId(new Long(""+year+week).longValue());
				try {
					System.out.println("CASE 4 - Modify Schedule - calling  msd.saveWeeklySchedule(ws)" );
					msd.deleteProgramSlots(ws);
					msd.saveWeeklySchedule(ws);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					System.out.println("CASE 4 - Modify Schedule - calling  msd.saveWeeklySchedule(ws) called ERROR" );
					e.printStackTrace();
					request.setAttribute("DISPLAY_MESSAGE", "Weekly Creation has generated error");
					RequestDispatcher req = getServletContext().getRequestDispatcher("/pages/modifySchedule.jsp");
					req.forward(request, response);
				}
//				success
				System.out.println("CASE 4 - Modify Schedule - calling  msd.saveWeeklySchedule(ws) called success" );
				request.setAttribute("DISPLAY_MESSAGE", "Weekly Schedule has been Modified ");
				RequestDispatcher req = getServletContext().getRequestDispatcher("/pages/modifySchedule.jsp");
				req.forward(request, response);
			}
					
			break;
		default:
			System.out.println("ScheduleController case DEFAULT START");
			
			System.out.println("CASE DEFSAULT - No action" );
			//request.setAttribute("DISPLAY_MESSAGE", "Weekly Schedule has been Modified ");
			RequestDispatcher req = getServletContext().getRequestDispatcher("/maintainSchedule.jsp");
			req.forward(request, response);
		}
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
	
	}
